/**
 * Created by Alice on 2016/9/19 0019
 */

var _tempHtml = $('#_stream_div').clone();
$(function () {
    $('.fa-plus-square-o').click(function () {
        $('#_stream_form').after(_tempHtml.html());
        $('.fa-minus-square-o').click(function () {
            $(this).parent().remove();
        });
    });
    $("#sys_court_status").find("a").attr("href", r.base_path + "system_monitor/sys_court_status?courtUid=" + r.court_uid);
    $("#sys_server_status").find("a").attr("href", r.base_path + "system_monitor/sys_server_status?courtUid=" + r.court_uid);
    selectAllCourtRoom();
    initcollapseOne();
    initcollapseTwo();
    $("#loading").hide();
});

function initcollapseOne() {
    $("#_export").click(function () {
        var courtname = $("#parentCourtList").find("option:selected").text();
        var form = document.getElementById("_form");
        // form.target="_blank";
        form.action = r.base_path + "device/exportCourtEquipment";
        var newElem = document.getElementById("fileTitle") ? document.getElementById("fileTitle") : document.createElement("input");
        newElem.setAttribute("name", "fileTitle");
        newElem.setAttribute("id", "fileTitle");
        newElem.setAttribute("type", "hidden");
        newElem.setAttribute("value", courtname);
        form.appendChild(newElem);
        form.submit();
        // $.get(basePath+"sys/courtEquipment/exportCourtEquipment", {courtId: courtId,courtName:$("#_search_eq").val()}, function (result) {
        //
        // });
        // layer.msg("开始导出！");
        // $.post(basePath+"sys/courtEquipment/exportCourtEquipment", {courtId: courtId,courtName:$("#_search_eq").val()}, function (result) {
        //
        // });
    })
}
function initcollapseTwo() {
    $("#add_courtequipment_btn").click(function () {
        $("#_uid").val("");
        document.getElementById("_form_eq").reset();
        selectCourtRoom($("#_court").val())
        $("#_editEqInfo").modal("show");
    });

    //法庭设备管理select的change事件
    $("#parentCourtList").change(function () {
        getSumNumberForCourtEquipment();
    });

    $("#_court").change(function () {
        selectCourtRoom($("#_court").val());
    });
    $("#_search_eq").click(function () {
        getSumNumberForCourtEquipment();
    });
    getSumNumberForCourtEquipment();
}

/**
 *  列出法庭
 */
function selectAllCourtRoom() {

    $("#parentCourtList").empty();
    $("#_court").empty();
    $.each(currentCourtList, function (i, n) {
        $("#parentCourtList").append("<option value='" + n.uid + "'>" + n.name + "</option>");
        $("#_court").append("<option value='" + n.uid + "'>" + n.name + "</option>");
    });
    selectCourtRoom(currentCourtList[0].uid);
}

//_________________________________法庭设置


function updateSumCounrtNumber() {
    var courtId = $("#parentCourtList").val();
    var sumNumber = $("#sumNumber").val();
    if (!isNaN(sumNumber)) {
        $.post(r.base_path + "sys/courtSetting/saveSumCourt", {courtid: courtId, num: sumNumber}, function (result) {
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.msg(result.msg);
            });

        });
    } else {
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.msg("请输入数字！");
        });

    }
}

function temp(htmlid, id, value) {
    // console.log(id, value);
    $(htmlid).find("button").html(value + '<span class="caret"></span>');
    $(htmlid).find("input").val(id);
}

var pageSize = 10;


function getCourtSettingByUid(cid) {
    $("#loading").show();
    $.ajax({
        url: r.base_path + "sys/courtSetting/getCourtSettingByCid",
        type: "post",
        data: {
            cid: cid
        },
        dataType: "json",
        success: function (result) {
            var data = result.data;
            // console.log(data);
            var courtName = data.court_name;
            var courtType = data.court_type;
            var streamIp = data.stream_address;
            var definition = data.definition;
            var vender = data.vender;
            var streamAddressList = streamIp.split(",");
            var channel = streamAddressList[0].split("<=>")[0];
            var stream = streamAddressList[0].split("<=>")[1];
            $(".courtNameForSetting").val(courtName);
            $(".court_room_type").val(courtType);
            $(".channelNameForStream").val(channel);
            $(".streamNameForStream").val(stream);
            $(".clearNameForSetting").val(definition);
            $(".venderForStream").val(vender);
            // $(".venderForStream option:contains('" + vender + "')").attr("selected", true);
            $(".avdevice").val(data.avdevice);
            $(".devicetype").val(data.devicetype);
            $(".activestatus").val(data.activestatus);
            $("#_cid").val(cid);
            $('.temp-div').remove();
            for (var int = 1; int < streamAddressList.length; int++) {
                channel = streamAddressList[int].split("<=>")[0];
                stream = streamAddressList[int].split("<=>")[1];
                var temp = _tempHtml.clone();
                temp.find('input').eq(0).attr("value", channel);
                temp.find('input').eq(1).attr("value", stream);
                $('#_stream_form').after(temp.html());
            }
            $('.fa-minus-square-o').click(function () {
                $(this).parent().remove();
            });
            $("#loading").hide();
            $('#_editCourtInfo').modal("show");
        },
        error: function () {
        }
    });
}

//修改法庭
function update_court_btn() {
    //获取法庭参数
    var courtName = $(".courtNameForSetting").val();
    var courtType = $(".court_room_type").val();
    var $channelNameList = $(".channelNameForStream");
    var $streamNameForStreamList = $(".streamNameForStream");
    var streamIp = "";
    for (var i = 0; i < $channelNameList.length; i++) {
        streamIp += $channelNameList.eq(i).val() + "<=>" + $streamNameForStreamList.eq(i).val() + ",";
    }
    streamIp = streamIp.substring(0, streamIp.length - 1);
    var definition = $(".clearNameForSetting").val();
    var vender = $(".venderForStream").val();
    var cid = $("#_cid").val();
    var parentCourt = $("#parentCourtList").find("option:selected").text();
    if (!parentCourt) {
        alert("法院不能为空！");
        return;
    }
    if (courtName == null || courtName == "") {
        alert("法庭名称不能为空");
        return;
    }
    if (courtType == null || courtType == "") {
        alert("法庭类型不能为空");
        return;
    }
    if (streamIp == null || streamIp == "") {
        alert("直播流地址不能为空");
        return;
    }
    if (definition == null || definition == "") {
        alert("清晰度不能为空");
        return;
    }
    if (vender == null || vender == "") {
        alert("厂商不能为空");
        return;
    }
    var _court_id = $("#parentCourtList").val();
    if (cid) {
        $.ajax({
            url: r.base_path + "sys/courtSetting/updateCourt",
            type: "post",
            dataType: "json",
            data: {
                cid: cid,
                court_name: courtName,
                court_type: courtType,
                stream_address: streamIp,
                parent_count: parentCourt,
                definition: definition,
                vender: vender,
                avdevice: $("#avdevice").val(),
                devicetype: $(".devicetype").val(),
                activestatus: $(".activestatus").val()
            },
            success: function (result) {
                layui.use('layer', function () {
                    var layer = layui.layer;
                    layer.msg("更新成功！");
                });
                $('#_editCourtInfo').modal("hide");
            },
            error: function () {
            }
        });
    } else {
        $.ajax({
            url: r.base_path + "sys/courtSetting/insertCourt",
            type: "post",
            dataType: "json",
            data: {
                court_id: _court_id,
                court_name: courtName,
                court_type: courtType,
                stream_address: streamIp,
                parent_count: parentCourt,
                definition: definition,
                vender: vender,
                avdevice: $("#avdevice").val(),
                devicetype: $(".devicetype").val(),
                activestatus: $(".activestatus").val()
            },
            success: function (result) {
                if (result.data != 0) {
                    layui.use('layer', function () {
                        var layer = layui.layer;
                        layer.msg("添加成功！");
                    });
                    $('#_editCourtInfo').modal("hide");
                }
            },
            error: function () {
            }
        });
    }


}

function deleteCourtInfo(cid) {
    $('#_deleteCourtInfo').find("input").val(cid);
    $('#_deleteCourtInfo').find(".modal-body").html("删除数据吗？");
    $('#_deleteCourtInfo').modal();
}
function deleteCourtInfoModal() {
    var val = $('#_deleteCourtInfo').find("input").val();
    $.ajax({
        url: r.base_path + "sys/courtSetting/deleteCourtByCid",
        type: "post",
        data: {
            cid: val
        },
        dataType: "json",
        success: function (result) {
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.msg("操作成功！");
            });
            $('#_deleteCourtInfo').modal('hide');
        },
        error: function () {
        }
    });
}

function page(now, totalPages, callback) {
    base.pagination('#_page', {
        currentPage: now,
        totalPages: totalPages,
        onPageClicked: function (page) {
            callback(page);
        }
    });
}

//_________________________________法庭设备管理
var emPageSize = 10;
function getSumNumberForCourtEquipment(pageIndex) {
    if(!pageIndex){
        pageIndex = 1;
    }
    var courtUid = $("#parentCourtList").val();
    var courtroomName = $("#search_courtequipment_input").val();
    $.ajax({
        url: r.base_path + "device/countDeviceByCourtUid",
        type: "post",
        data: {
            courtUid: courtUid,
            courtroomName: courtroomName,
            page: pageIndex,
            pageSize: emPageSize
        },
        dataType: "json",
        success: function (result) {
            // console.log(result);
            if (result.data.count == 0) {
                pageEq(1, 1, null);
            } else {
                pageEq(pageIndex, Math.ceil(result.data.count / pageSize), getSumNumberForCourtEquipment);
            }

            $('#tableDivId2').empty();
            var tr = ' <table id="table2" class="table table-bordered text-center" ></table>';
            $('#tableDivId2').append(tr);
            $('#table2').bootstrapTable({
                columns: [{
                    field: 'id',
                    title: '编号',
                    width: '5.3%',
                    formatter: function (value, row, index) {
                        return (index + 1) > 9 ? index + 1 : '0' + (index + 1);
                    }
                }, {
                    field: 'courtRoomName',
                    title: '法庭名称'
                }, {
                    field: 'num',
                    title: '设备编号'
                }, {
                    field: 'name',
                    title: '设备名称'
                }, {
                    field: 'type',
                    title: '设备型号'
                }, {
                    field: 'position',
                    title: '设备位置'
                }, {
                    field: 'statusName',
                    title: '设备状态'
                }, {
                    field: 'context',
                    title: '说明'
                }, {
                    field: 'edit',
                    title: '操作',
                    class: 'center se_operation',
                    formatter: function (value, row) {
                        // console.log(row.uid);
                        var html = '<a href="javascript:selectCourtequipment(\'' + row.id + '\')"><i class="fa fa-edit fa-lg"></i></a>&nbsp;<a href="javascript:deleteCourtequipment(\'' + row.id + '\')" ><i class="fa fa-trash-o fa-lg"></i></a>'
                        return html;
                    }
                }
                ],

                data: result.data.data
            })
            $("#court_equipment_table").show();
        },
        error: function () {
        }
    });
}


function selectCourtRoom(courtUid) {
    $("#_courtRoom").empty();
    $.each(courtroomList, function (i, n) {
        if(n.courtUid == courtUid && n.active == 1){
            $("#_courtRoom").append("<option value='" + n.uid + "'>" + n.name + "</option>");
        }
    });
}

function selectCourtequipment(id) {
    $.post(r.base_path + "device/selectDeviceByPrimaryKey", {id: id}, function (result) {
        if (result.data) {
            $("#_uid").val(id);
            $("._court").val(result.data.courtUid);
            $("#_courtRoom").val(result.data.courtRoomUid);
            $("#_devno").val(result.data.num);
            $("#_devname").val(result.data.name);
            $("#_devtype").val(result.data.type);
            $("#_devpos").val(result.data.position);
            $("#_devstatus").val(result.data.status);
            $("#_devmemo").val(result.data.context);
            $("#_editEqInfo").modal("show");
        }
    }, 'json')
}
function deleteCourtequipment(id) {
    $('#_deleteEqInfo').find("input").val(id);
    $('#_deleteEqInfo').find(".modal-body").html("删除编号《  " + id + "  》的数据吗？");
    $('#_deleteEqInfo').modal();
}
function deleteEqInfoModal() {
    var val = $('#_deleteEqInfo').find("input").val();
    $.ajax({
        url: r.base_path + "device/deleteDeviceByPrimaryKey",
        type: "post",
        data: {
            id: val
        },
        dataType: "json",
        success: function (result) {
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.msg("操作成功！");
            });
            getSumNumberForCourtEquipment();
            $('#_deleteEqInfo').modal('hide');
        },
        error: function () {
        }
    });
}

function addCourtEquipment() {

    var courtUid = $("#_court").val();
    var courtroomUid = $("#_courtRoom").val();
    var num = $("#_devno").val();
    var name = $("#_devname").val();
    var type = $("#_devtype").val();
    var position = $("#_devpos").val();
    var status = $("#_devstatus").val();
    var context = $("#_devmemo").val();
    var _uid = $("#_uid").val();
    if (courtroomUid == null || courtroomUid == "") {
        alert("法庭名称不能为空");
        return;
    }
    if (_uid) {
        $.post(r.base_path + "device/updateDevice", {
            id: _uid,
            courtUid: courtUid,
            courtRoomUid: courtroomUid,
            num: num,
            name: name,
            type: type,
            position: position,
            status: status,
            context: context
        }, function (result) {
            if (result.code == 0) {
                layui.use('layer', function () {
                    var layer = layui.layer;
                    layer.msg("修改成功");
                });
                getSumNumberForCourtEquipment();
                $("#_editEqInfo").modal("hide");
            }
        }, 'json');
    } else {
        $.ajax({
            url: r.base_path + "device/addDevice",
            type: "post",
            dataType: "json",
            data: {
                courtUid: courtUid,
                courtRoomUid: courtroomUid,
                num: num,
                name: name,
                type: type,
                position: position,
                status: status,
                context: context
            },
            success: function (result) {
                if (result.code == 0) {
                    layui.use('layer', function () {
                        var layer = layui.layer;
                        layer.msg("添加成功！");
                    });
                    getSumNumberForCourtEquipment();
                    $("#_editEqInfo").modal("hide");
                }
            },
            error: function () {
            }
        });
    }
}

function pageEq(now, totalPages, callback) {
    base.pagination('#_page_eq', {
        currentPage: now,
        totalPages: totalPages,
        onPageClicked: function (page) {
            callback(page);
        }
    });
}